package com.rainbow.interceptor;

import cn.hutool.core.lang.Console;
import com.rainbow.annotation.NoLogin;
import com.rainbow.entity.Token;
import com.rainbow.expetion.MyException;
import com.rainbow.service.TokenService;
import com.rainbow.utils.ApiUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @Author rainbow
 **/
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
    public static final String USER_KEY = "userId";

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        NoLogin annotation;
        Console.log("拦截器校验");
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(NoLogin.class);
        } else {
            return true;
        }
        if (null != annotation) {
            return true;
        }


        // 从header中获取token
        String token = request.getHeader("token");
        // 如果header中不存在token，则从参数中获取token
        if (token == null || token.isBlank()) {
            token = request.getParameter("token");
        }
        // token为空
        if (token == null || token.isBlank()) {
            throw new MyException("token 不能为空");
        }
        // 查询token信息
        Token token1 = tokenService.queryByToken(token);
        if (token1 == null || token1.getExpireTime().getTime() < System.currentTimeMillis()) {
            throw new MyException("token失效，请重新登录！！");
        }
        Date date = ApiUtils.getFutureTime(1);
        token1.setExpireTime(date);
        token1.setUpdateTime(new Date());
        tokenService.updateById(token1);

        //设置userId到request里，后续根据userId，获取用户信息
        request.setAttribute(USER_KEY, token1.getUserId());
        return true;
    }
}
